package com.iguo.tube.util;

import com.iguo.tube.model.Point;

public class HaversineDistance {
  private static final double R = 6371000; // 地球半径，单位：米
  public static int haversine(Point point1,Point point2) {

    double lat1 = transToDouble(point1.getLat());
    double lat2 = transToDouble(point2.getLat());
    double lon1 = transToDouble(point1.getLng());
    double lon2 = transToDouble(point2.getLng());

    // 将角度转换为弧度
    double lat1Rad = Math.toRadians(lat1);
    double lon1Rad = Math.toRadians(lon1);
    double lat2Rad = Math.toRadians(lat2);
    double lon2Rad = Math.toRadians(lon2);

    // 计算差值
    double dLat = lat2Rad - lat1Rad;
    double dLon = lon2Rad - lon1Rad;

    // 哈弗辛公式
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                    Math.sin(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // 计算距离
    //System.out.println( " " + point1.getName() + " -> " + point2.getName() + " " +  (int)( R*c ) + "米");
    return (int)( R*c ); // 返回结果，单位：米
  }

  public static double transToDouble(String str){
      Double doubleValue = Double.parseDouble(str);
      return doubleValue;
  }

  public static void main(String[] args){
    Point point1 = new Point(1,"1","39.917408","119.521000",1,0);
    Point point2 = new Point(2,"2","39.916000","119.539000",2,0);
    Point point3 = new Point(2,"2","39.916000","119.539000",2,0);
    System.out.println(haversine(point1,point2));
  }
}
